//
//  TransitionConfigForInteractive.swift
//  Swift-app开发基础架构
//
//  Created by pro on 2017/8/16.
//  Copyright © 2017年 com.itboye. All rights reserved.
//

import UIKit

class KZInteractiveTransition: UIPercentDrivenInteractiveTransition {

    /// 是否允许交互
    var interation = false
    /// 手势开始时执行的代码
    var interactiveClouse: (()->())?
    
    
    private var _percent: CGFloat = 0.0
    private var _timeDis: CGFloat = 0.0
    private var _timer: CADisplayLink?
    
    func addGesture(toView view: UIView) {
        
        let ges = UIScreenEdgePanGestureRecognizer(target: self, action:#selector(panAction(_:)))
        ges.edges = .left
        view.addGestureRecognizer(ges)
    }
    
    @objc private func panAction(_ pan: UIScreenEdgePanGestureRecognizer) {
        
        let point = pan.translation(in: pan.view)
        let offsetX = point.x
        switch pan.state {
        case .began:
            interation = true
            if let clouse = interactiveClouse {
                clouse()
            }
            _update()
            
        case .changed:
            _percent = offsetX / kScreenWidth
            _update()

        case .ended:
            startTimer(_percent)
        default: break
        }
    }
    
    
    
    private func _update() {
        
        update(_percent)
    }
    private func _cancel() {
        
        if _percent > 0.5 {
            _finish()
        } else {
            cancel()
            _percent = 0.0
            interation = false
        }
    }
    private func _finish() {
        finish()
        _percent = 0.0
        interation = false
    }
    
    private func startTimer(_ percent: CGFloat) {
        _percent = percent
        if (percent > 0.5) {
            _timeDis = (1 - percent) / ((1 - percent) * 60);
        } else {
            _timeDis = percent / (percent * 60);
        }
        
        if _timer != nil {
            return
        } else {
            _timer = CADisplayLink(target: self, selector: #selector(timerAction))
            _timer?.add(to: RunLoop.current, forMode: .commonModes)
        }

    }
    
    @objc private func timerAction() {
        
        if _percent > 0.5 {
            _percent += _timeDis
        } else {
            _percent -= _timeDis
        }
        _update()
        if _percent >= 1 {
            _finish()
            _timer?.invalidate()
            _timer = nil
        } else {
            _cancel()
            _timer?.invalidate()
            _timer = nil
        }
    }
}

